﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NguyenHoa.Web.App_Code;
using NguyenHoa.Domains;
using NguyenHoa.Services;
using System.Web.UI.HtmlControls;

namespace NguyenHoa.Web.Admin
{
  public partial class ProductDetail : AdminBasePage
  {
    #region Properties
    private string m_innerError = string.Empty;
    private string ERROR0001 = "error:save|";

    private string m_checkBoxList = string.Empty;
    private string m_allIdList = string.Empty;

    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.Product;
      }
    }

    internal override void SetPermission()
    {
      if (!CanModify) btnSave.Visible = false;
    }

    private int ProductId
    {
      get
      {
        int productId = 0;
        int.TryParse(hfProductId.Value, out productId);
        return productId;
      }

      set
      {
        hfProductId.Value = value.ToString();
      }
    }

    private int LocaleId
    {
      set
      {
        hfLocaleId.Value = value.ToString();
      }

      get
      {
        int Id = 0;
        if (!string.IsNullOrEmpty(hfLocaleId.Value))
          int.TryParse(hfLocaleId.Value, out Id);
        return Id;
      }
    }

    private int AlbumId
    {
      get
      {
        int albumId = 0;
        int.TryParse(hfAlbumId.Value, out albumId);
        return albumId;
      }

      set
      {
        hfAlbumId.Value = value.ToString();
      }
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      SettingUpload();
      if (!IsPostBack && !IsCallback)
      {
        LoadPage();
      }
    }

    protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      if (e.Parameter.StartsWith("save"))
      {
        e.Result = SaveLocale();
        return;
      }
      if (e.Parameter.StartsWith("language"))
      {
        e.Result = ChangeLocale();
      }
    }

    protected void dvList_CustomCallback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
      string[] para = e.Parameter.Split('|');
      switch (para[0])
      {
        case "Save":
          m_innerError = SavePhoto();
          break;
        case "Delete":
          m_innerError = DeletePhoto(para[1]);
          LoadPhoto(AlbumId);
          break;
      }

      if (m_innerError.Contains("OK"))
      {
        m_innerError += m_checkBoxList + "|" + m_allIdList;
      }
    }

    protected void dvList_CustomJSProperties(object sender, DevExpress.Web.ASPxClasses.CustomJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void dvList_DataBound(object sender, EventArgs e)
    {
      if (dvList.DataSource == null) return;
      hfCheckBoxList.Value = string.Empty;
      hfAllIdList.Value = string.Empty;
      m_allIdList = string.Empty;
      m_checkBoxList = string.Empty;
      for (int i = 0; i < dvList.Items.Count; i++)
      {
        HtmlInputCheckBox ckbox = dvList.FindItemControl("item_checkbox", dvList.Items[i]) as HtmlInputCheckBox;
        if (ckbox != null)
        {
          Domains.Multimedia photo = dvList.Items[i].DataItem as Domains.Multimedia;
          if (photo != null)
          {
            ckbox.Attributes.Add("onclick", "onSelect('" + photo.Id + "', this.checked)");
            hfAllIdList.Value += photo.Id + ",";
            m_allIdList += photo.Id + ",";
          }

          hfCheckBoxList.Value += ckbox.ClientID + ",";
          m_checkBoxList += ckbox.ClientID + ",";
        }
      }
    }
    #endregion

    #region Methods
    private void LoadPage()
    {
      lblNote.Text = "(*) " + Resources.Strings.ImgSizeProduct;
      int productId = 0;
      if (int.TryParse(Request.QueryString["id"], out productId))
      {
        Product product = new ProductService().GetById(productId);
        if (product != null)
        {
          ProductId = productId;
          if (product.AlbumId.HasValue)
          {
            AlbumId = product.AlbumId.Value;
            LoadPhoto(AlbumId);
          }

          xdsLanguage.DataFile = XmlStatusFile;
          cbbLanguage.Value = CurrentLanguage.Id;
          LoadLocale();
          return;
        }
      }

      Response.Redirect("ProductList.aspx");
    }

    #region Methods Info
    private string SaveLocale()
    {
      try
      {
        if (string.IsNullOrEmpty(txtName.Text.Trim()))
        {
          return ERROR0001 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
        }

        //update
        if (LocaleId != 0)
        {
          return UpdateLocale();
        }

        //insert
        ProductLocale pl = new ProductLocale();
        SetContainProductLocale(pl);
        ProductLocale np = new ProductLocaleService().Save(pl);

        return "save|" + np.Id.ToString();

      }
      catch (Exception ex)
      {
        WriteLog("ProductDetail.aspx::Save Product", ex);
        return ERROR0001 + Resources.Messages.ERR0054;
      }
    }

    private string ChangeLocale()
    {
      TList<ProductLocale> plList = new ProductLocaleService().GetByProductId(ProductId);
      foreach (ProductLocale item in plList)
      {
        if (item.LanguageId == (int)cbbLanguage.Value)
        {
          return string.Format("[language]ok|{0}|{1}|{2}|{3}|{4}", item.Name, item.Description, item.RefPrice, item.Content, item.Id);
        }
      }

      return string.Format("[language]ok|{0}|{1}|{2}|{3}|{4}", string.Empty, string.Empty, 0, string.Empty, 0);
    }

    private string UpdateLocale()
    {
      try
      {
        ProductLocaleService pls = new ProductLocaleService();
        ProductLocale pl = pls.GetById(LocaleId);
        SetContainProductLocale(pl);
        pls.Update(pl);
        return "save[update]";
      }
      catch (Exception ex)
      {
        WriteLog("ProductLocale::Update ProductLocale", ex);
        return ERROR0001 + "|" + Resources.Messages.ERR0054;
      }
    }

    private void SetContainProductLocale(ProductLocale pl)
    {
      pl.ProductId = ProductId;
      pl.LanguageId = (int)cbbLanguage.Value;
      pl.Description = mmSummary.Text;
      pl.Content = hdContent.Html;
      decimal price = 0;
      decimal.TryParse(txtPrice.Text.Trim(), out price);
      pl.RefPrice = price;
      pl.Name = txtName.Text.Trim();
    }

    private void LoadLocale()
    {
      TList<ProductLocale> plList = new ProductLocaleService().GetByProductId(ProductId);
      foreach (ProductLocale item in plList)
      {
        if (item.LanguageId == CurrentLanguage.Id)
        {
          txtName.Text = item.Name;
          mmSummary.Text = item.Description;
          txtPrice.Text = item.RefPrice.ToString();
          hdContent.Html = item.Content;
          LocaleId = item.Id;
        }
      }
    }
    #endregion

    #region Methods Photo
    private void SettingUpload()
    {
      MultiUpload1.FileType = AllowFileContentType.Image;
      MultiUpload1.UploadCompleteFunction = "UploadComplete";
      MultiUpload1.UploadSessionName = SessionName.Upload_ContainPostedFile;
      MultiUpload1.UploadFolder = FolderDirector.Photo;
      MultiUpload1.NoticeMessage = Resources.Messages.ERR0024;
    }

    private void LoadPhoto(int albumId)
    {
      TList<Multimedia> pList = new MultimediaService().GetByAlbumId(albumId);
      foreach (Multimedia photo in pList)
      {
        if (!string.IsNullOrEmpty(photo.Path))
        {
          photo.Path = "../" + photo.Path;
        }
      }

      dvList.DataSource = pList;
      dvList.DataBind();
    }

    private string SavePhoto()
    {
      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          AlbumService aService = new AlbumService();
          Album album = aService.GetById(AlbumId);
          if (album == null)
          {
            ProductService pService = new ProductService();
            Product product = pService.GetById(ProductId);

            album = new Album();
            album.Name = product.Name;
            album.Type = AlbumType.Product;
            album.Status = VisibleStatus.Active;
            album.CreatedDate = DateTime.Now;
            album.CreatedBy = CurrentUser.Username;
            aService.Save(album);

            product.AlbumId = album.Id;
            product.ModifiedDate = DateTime.Now;
            product.ModifiedBy = CurrentUser.Username;
            pService.Update(product);
          }
          else
          {
            album.ModifiedDate = DateTime.Now;
            album.ModifiedBy = CurrentUser.Username;
            aService.Save(album);
          }

          MultimediaService mService = new MultimediaService();
          TList<Multimedia> pList = new TList<Multimedia>();
          string uploadedList = string.Empty;
          if (Session[SessionName.Upload_ReturnFiles] != null)
            uploadedList = Session[SessionName.Upload_ReturnFiles].ToString();

          if (!string.IsNullOrEmpty(uploadedList))
          {
            string[] fileList = uploadedList.Split(';');
            for (int i = 0; i < fileList.Length; i++)
            {
              if (string.IsNullOrEmpty(fileList[i]))
                continue;
              Multimedia photo = new Multimedia();
              photo.Path = fileList[i];
              photo.PostedBy = CurrentUser.Username;
              photo.PostedDate = DateTime.Now;
              photo.AlbumId = album.Id;
              photo.Type = MultimediaType.Photo;
              photo.Status = VisibleStatus.Active;

              pList.Add(photo);
            }
          }

          ClearSession(new string[] { SessionName.Upload_ReturnFiles, SessionName.Upload_ContainPostedFile });
          if (pList.Count > 0)
          {
            mService.Save(pList);
            ConnectionScope.Complete();
            LoadPhoto(album.Id);

            return "SaveOK|" + album.Id.ToString() + '|';
          }
        }
      }
      catch (Exception ex)
      {
        WriteLog("PhotoList.aspx::Save Photo", ex);
        return Resources.Messages.ERR0004;
      }

      return string.Empty;
    }

    private string DeletePhoto(string deletedList)
    {
      try
      {
        if (!string.IsNullOrEmpty(deletedList))
        {
          MultimediaService pService = new MultimediaService();
          if (deletedList.EndsWith(","))
            deletedList = deletedList.Remove(deletedList.Length - 1);
          string[] idList = deletedList.Split(',');
          string[] imagePath = new string[idList.Length];
          for (int i = 0; i < idList.Length; i++)
          {
            if (string.IsNullOrEmpty(idList[i]))
              continue;
            int id = 0;
            int.TryParse(idList[i], out id);
            Domains.Multimedia photo = pService.GetById(id);
            if (photo != null)
            {
              string filePath = @MapPath("~\\" + photo.Path);
              imagePath[i] = filePath;
            }
          }

          pService.DeleteByIdList(deletedList);
        }
      }
      catch (Exception ex)
      {
        WriteLog("PhotoList.aspx::Delete Photo", ex);
        return Resources.Messages.ERR0004;
      }

      return "DeleteOK|" + AlbumId.ToString() + '|';
    }
    #endregion
    #endregion
  }
}
